/*
 * Logger.java
 *
 * Created on August 23, 2005, 2:40 PM
 *
 * This class encapsulates log message sending
 */

package oracle.olapi.examples;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;


/**
 *
 * @author mruokone
 */
public class Logger {
    
    private PrintWriter writer = null;
    
    /**
     * Produce more detailed output during program execution?
     */
    private boolean verbose = true;
    
    public Logger() {}
    
    public Logger(PrintWriter out) {
        setWriter(out);
    }
    
    public Logger(Writer out) {
        this(new PrintWriter(out));
    }
    
    /**
     * Getter for property verbose.
     * @return Value of property verbose.
     */
    public boolean isVerbose() {
        return this.verbose;
    }
    
    /**
     * Setter for property verbose.
     * @param verbose New value of property verbose.
     */
    public void setVerbose(boolean verbose) {        
        this.verbose = verbose;
    }
    public PrintWriter getPrintWriter() {
        return writer;
    }
    
    public void setWriter(PrintWriter writer) {
        close(); // in case we switch writers: close current writer
        this.writer = writer;
    }
    
    /**
     * Convinience method for output streams - does buffering as well
     */
    public void setWriter(PrintStream os) {
        setWriter(new PrintWriter(
                new BufferedWriter(
                new OutputStreamWriter(os))));
        
    }
    
    protected void initWriter() {
        if ( writer == null )
            setWriter(System.out);
    }
    
    public void println(String message) {
        initWriter();
        writer.println(message);
    }
    
    public void print(String message) {
        initWriter();
        writer.print(message);
    }
    
    public void println() {
        initWriter();
        writer.println();
    }
    
    public void showInfo(String message) {
        if ( isVerbose() ) {
            initWriter();
            writer.println(message);
        }
    }
    
    public void showError(String message) {
        initWriter();
        writer.print("ERROR: ");
        writer.println(message);
    }
    
    public void close() {
        if ( null != writer ) {
            writer.flush();
            writer = null;
        }
    }
}
